<template>
  <div class="role-management">
    <div class="page-header">
      <div class="header-actions">
        <button @click="openAddModal" class="btn btn-primary">
          ➕ 新增角色
        </button>
        <button @click="loadData" class="btn btn-secondary">
          🔄 刷新
        </button>
      </div>
      <div class="search-box">
        <input 
          v-model="searchQuery" 
          type="text" 
          placeholder="🔍 搜索角色名称或描述..."
          class="search-input"
        />
      </div>
    </div>

    <div class="role-table">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>角色名称</th>
            <th>描述</th>
            <th>角色类型</th>
            <th>权限数量</th>
            <th>关联用户组</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="filteredRoles.length === 0">
            <td colspan="8" class="no-data">暂无角色数据</td>
          </tr>
          <tr v-for="role in filteredRoles" :key="role.id">
            <td>{{ role.id }}</td>
            <td>{{ role.name }}</td>
            <td>{{ role.description || '-' }}</td>
            <td>
              <span :class="['badge', getRoleTypeClass(role.role_type)]">
                {{ getRoleTypeName(role.role_type) }}
              </span>
            </td>
            <td>
              <span class="permission-count">{{ role.permission_count }} 个</span>
            </td>
            <td>
              <div class="user-groups">
                <span v-if="!role.user_groups || role.user_groups.length === 0" class="no-group">-</span>
                <template v-else>
                  <span v-for="group in role.user_groups.slice(0, 3)" :key="group" class="group-tag">
                    {{ group }}
                  </span>
                  <span v-if="role.user_groups.length > 3" class="more-tag">
                    +{{ role.user_groups.length - 3 }}
                  </span>
                </template>
              </div>
            </td>
            <td>{{ formatDate(role.created_at) }}</td>
            <td>
              <div class="action-buttons">
                <button @click="openEditModal(role)" class="btn-action btn-edit">✏️ 编辑</button>
                <button @click="openPermissionModal(role)" class="btn-action btn-permission">🔑 权限</button>
                <button @click="deleteRole(role.id)" class="btn-action btn-delete">🗑️ 删除</button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 新增/编辑角色弹窗 -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ isEdit ? '编辑角色' : '新增角色' }}</h3>
          <button @click="closeModal" class="close-btn">✕</button>
        </div>
        <form @submit.prevent="saveRole">
          <div class="form-group">
            <label>角色名称 *</label>
            <input v-model="formData.name" required placeholder="请输入角色名称" />
          </div>
          <div class="form-group">
            <label>描述</label>
            <textarea v-model="formData.description" placeholder="请输入角色描述" rows="3"></textarea>
          </div>
          <div class="form-group">
            <label>角色类型 *</label>
            <select v-model="formData.role_type" required>
              <option value="custom">自定义角色</option>
              <option value="system">系统角色</option>
            </select>
          </div>
          <div class="form-group">
            <label>关联用户组</label>
            <div v-if="allGroups.length === 0" style="color: #999; padding: 15px;">
              暂无可用的用户组
            </div>
            <div v-else class="checkbox-group">
              <label v-for="group in allGroups" :key="group.id" class="checkbox-label">
                <input 
                  type="checkbox" 
                  :value="group.id" 
                  v-model="formData.user_group_ids"
                  :id="`group-${group.id}`"
                />
                {{ group.name }}
              </label>
            </div>
          </div>
          <div class="modal-footer">
            <button type="submit" class="btn btn-primary">保存</button>
            <button type="button" @click="closeModal" class="btn btn-secondary">取消</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 权限管理弹窗 -->
    <div v-if="showPermissionModal" class="modal-overlay" @click="closePermissionModal">
      <div class="modal-content permission-modal" @click.stop>
        <div class="modal-header">
          <h3>🔑 权限管理 - {{ currentRole?.name }}</h3>
          <button @click="closePermissionModal" class="close-btn">✕</button>
        </div>
        <div class="permission-content">
          <div class="permission-category" v-for="category in permissionCategories" :key="category.name">
            <h4>{{ category.label }}</h4>
            <div class="permission-list">
              <label v-for="perm in category.permissions" :key="perm.value" class="permission-item">
                <input 
                  type="checkbox" 
                  :value="perm.value" 
                  v-model="selectedPermissions"
                />
                <span>{{ perm.label }}</span>
              </label>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="savePermissions" class="btn btn-primary">保存权限</button>
          <button @click="closePermissionModal" class="btn btn-secondary">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import api from '../services/api'

const roles = ref([])
const allGroups = ref([])
const searchQuery = ref('')
const showModal = ref(false)
const showPermissionModal = ref(false)
const isEdit = ref(false)
const currentRole = ref(null)
const selectedPermissions = ref([])

const formData = ref({
  name: '',
  description: '',
  role_type: 'custom',
  user_group_ids: []
})

// 权限分类
const permissionCategories = ref([
  {
    name: 'host',
    label: '主机管理',
    permissions: [
      { value: 'host.view', label: '查看主机' },
      { value: 'host.add', label: '添加主机' },
      { value: 'host.edit', label: '编辑主机' },
      { value: 'host.delete', label: '删除主机' },
      { value: 'host.ssh', label: 'SSH连接' }
    ]
  },
  {
    name: 'user',
    label: '用户管理',
    permissions: [
      { value: 'user.view', label: '查看用户' },
      { value: 'user.add', label: '添加用户' },
      { value: 'user.edit', label: '编辑用户' },
      { value: 'user.delete', label: '删除用户' }
    ]
  },
  {
    name: 'ansible',
    label: 'Ansible管理',
    permissions: [
      { value: 'ansible.view', label: '查看任务' },
      { value: 'ansible.execute', label: '执行任务' },
      { value: 'ansible.manage', label: '管理配置' }
    ]
  },
  {
    name: 'system',
    label: '系统管理',
    permissions: [
      { value: 'system.view', label: '查看系统信息' },
      { value: 'system.config', label: '系统配置' },
      { value: 'system.audit', label: '审计日志' }
    ]
  }
])

const filteredRoles = computed(() => {
  if (!searchQuery.value) return roles.value
  const query = searchQuery.value.toLowerCase()
  return roles.value.filter(role => 
    role.name.toLowerCase().includes(query) ||
    (role.description && role.description.toLowerCase().includes(query))
  )
})

const loadData = async () => {
  try {
    const [rolesData, groupsData] = await Promise.all([
      api.getRoles(),
      api.getGroups()  // 使用Django Groups而不是UserManagement Groups
    ])
    
    // 处理角色数据
    let rolesList = Array.isArray(rolesData) ? rolesData : (rolesData.results || [])
    
    // 确保每个角色都有user_groups数组和user_group_ids数组
    rolesList = rolesList.map(role => ({
      ...role,
      user_groups: role.user_groups || [],
      // 使用 user_group_ids_display 作为显示的 user_group_ids
      user_group_ids: role.user_group_ids_display || [],
      permission_count: role.permission_count || 0
    }))
    
    roles.value = rolesList
    allGroups.value = Array.isArray(groupsData) ? groupsData : (groupsData.results || [])
    
    console.log('加载的角色数据:', roles.value)
    console.log('可用的用户组:', allGroups.value)
  } catch (error) {
    console.error('加载数据失败:', error)
    alert('加载数据失败: ' + (error.message || '未知错误'))
  }
}

const openAddModal = () => {
  isEdit.value = false
  formData.value = {
    name: '',
    description: '',
    role_type: 'custom',
    user_group_ids: []
  }
  console.log('打开新增弹窗 - 可用的用户组:', allGroups.value)
  console.log('表单数据:', formData.value)
  showModal.value = true
}

const openEditModal = (role) => {
  isEdit.value = true
  formData.value = {
    ...role,
    user_group_ids: role.user_group_ids || []
  }
  console.log('打开编辑弹窗 - 角色数据:', role)
  console.log('表单数据:', formData.value)
  console.log('可用的用户组:', allGroups.value)
  showModal.value = true
}

const closeModal = () => {
  showModal.value = false
}

const saveRole = async () => {
  try {
    console.log('准备保存角色，表单数据:', formData.value)
    console.log('选中的用户组IDs:', formData.value.user_group_ids)
    
    // 准备提交的数据，只包含需要的字段
    const submitData = {
      name: formData.value.name,
      description: formData.value.description,
      role_type: formData.value.role_type,
      permissions: formData.value.permissions || [],
      user_group_ids: formData.value.user_group_ids || []
    }
    
    console.log('提交的数据:', submitData)
    
    if (isEdit.value) {
      const response = await api.updateRole(formData.value.id, submitData)
      console.log('更新角色响应:', response)
    } else {
      const response = await api.createRole(submitData)
      console.log('创建角色响应:', response)
    }
    alert('保存成功！')
    closeModal()
    loadData()
  } catch (error) {
    console.error('保存失败:', error)
    console.error('错误详情:', error.response?.data)
    alert('保存失败: ' + (error.response?.data?.error || error.message))
  }
}

const deleteRole = async (id) => {
  if (!confirm('确定要删除这个角色吗？')) return
  try {
    await api.deleteRole(id)
    alert('删除成功！')
    loadData()
  } catch (error) {
    console.error('删除失败:', error)
    alert('删除失败: ' + (error.response?.data?.error || error.message))
  }
}

const openPermissionModal = (role) => {
  currentRole.value = role
  selectedPermissions.value = [...(role.permissions || [])]
  showPermissionModal.value = true
}

const closePermissionModal = () => {
  showPermissionModal.value = false
  currentRole.value = null
}

const savePermissions = async () => {
  try {
    await api.updateRolePermissions(currentRole.value.id, {
      permissions: selectedPermissions.value
    })
    alert('权限保存成功！')
    closePermissionModal()
    loadData()
  } catch (error) {
    console.error('保存权限失败:', error)
    alert('保存权限失败: ' + (error.response?.data?.error || error.message))
  }
}

const getRoleTypeName = (type) => {
  const typeMap = {
    'custom': '自定义角色',
    'system': '系统角色'
  }
  return typeMap[type] || type
}

const getRoleTypeClass = (type) => {
  return type === 'custom' ? 'badge-custom' : 'badge-system'
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 监听用户组选择变化
watch(() => formData.value.user_group_ids, (newVal) => {
  console.log('用户组选择发生变化:', newVal)
}, { deep: true })

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.role-management {
  padding: 20px;
  background: #f8f9fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-box {
  flex: 1;
  max-width: 400px;
}

.search-input {
  width: 100%;
  padding: 10px 15px;
  border: 1px solid #FFB6C1;
  border-radius: 20px;
  background: white;
  color: #333;
  font-size: 14px;
}

.search-input::placeholder {
  color: #999;
}

.search-input:focus {
  outline: none;
  border-color: #FF69B4;
  box-shadow: 0 0 0 3px rgba(255, 182, 193, 0.2);
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-primary {
  background: linear-gradient(135deg, #FF69B4, #FF1493);
  color: white;
  box-shadow: 0 2px 8px rgba(255, 105, 180, 0.3);
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 105, 180, 0.4);
}

.btn-secondary {
  background: white;
  color: #FF69B4;
  border: 1px solid #FFB6C1;
}

.btn-secondary:hover {
  background: #FFF0F5;
  border-color: #FF69B4;
}

.role-table {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

table {
  width: 100%;
  border-collapse: collapse;
}

thead {
  background: linear-gradient(135deg, #FFE4E1, #FFF0F5);
}

th {
  padding: 15px;
  text-align: left;
  color: #FF1493;
  font-weight: 700;
  font-size: 14px;
  border-bottom: 2px solid #FFB6C1;
}

td {
  padding: 15px;
  color: #333;
  font-weight: 500;
  border-bottom: 1px solid #f0f0f0;
}

tbody tr {
  background: white;
}

tbody tr:hover {
  background: #FFF5F7;
}

.no-data {
  text-align: center;
  color: #999;
  padding: 40px;
}

.badge {
  padding: 6px 14px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  display: inline-block;
}

.badge-custom {
  background: white;
  border: 2px solid #87CEEB;
  color: #4682B4;
}

.badge-system {
  background: white;
  border: 2px solid #FFB6C1;
  color: #FF69B4;
}

.permission-count {
  color: #00BFFF;
  font-weight: 700;
  font-size: 14px;
}

.user-groups {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.no-group {
  color: #999;
  font-style: italic;
}

.group-tag {
  padding: 6px 12px;
  background: white;
  border: 2px solid #FFB6C1;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  color: #FF69B4;
}

.more-tag {
  padding: 6px 12px;
  background: white;
  border: 2px solid #87CEEB;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  color: #4682B4;
}

.action-buttons {
  display: flex;
  gap: 6px;
}

.btn-action {
  padding: 8px 16px;
  border: none;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.btn-edit {
  background: linear-gradient(135deg, #87CEEB, #4682B4);
  color: white;
}

.btn-edit:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(70, 130, 180, 0.4);
}

.btn-permission {
  background: linear-gradient(135deg, #FFB6C1, #FF69B4);
  color: white;
}

.btn-permission:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(255, 105, 180, 0.4);
}

.btn-delete {
  background: linear-gradient(135deg, #FF7F7F, #FF6B6B);
  color: white;
}

.btn-delete:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(255, 107, 107, 0.4);
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.modal-content {
  background: white;
  border: 2px solid #FFB6C1;
  border-radius: 16px;
  padding: 30px;
  min-width: 500px;
  max-width: 800px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

.permission-modal {
  min-width: 700px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #FFE4E1;
}

.modal-header h3 {
  color: #FF1493;
  font-size: 20px;
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  color: #999;
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s;
}

.close-btn:hover {
  background: #FFE4E1;
  color: #FF1493;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  color: #333;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 600;
}

.form-group input:not([type="checkbox"]),
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 10px 12px;
  background: white;
  border: 1px solid #FFB6C1;
  border-radius: 8px;
  color: #333;
  font-size: 14px;
  transition: all 0.3s;
}

.form-group input:not([type="checkbox"]):focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #FF69B4;
  box-shadow: 0 0 0 3px rgba(255, 182, 193, 0.2);
}

.checkbox-group {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 10px;
  padding: 15px;
  background: #FFF5F7;
  border-radius: 8px;
  border: 1px solid #FFE4E1;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #333;
  cursor: pointer;
  padding: 4px;
}

.checkbox-label:hover {
  color: #FF1493;
}

.checkbox-label input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
  accent-color: #FF69B4;
  flex-shrink: 0;
}

.permission-content {
  max-height: 500px;
  overflow-y: auto;
}

.permission-category {
  margin-bottom: 24px;
}

.permission-category h4 {
  color: #FF1493;
  font-size: 16px;
  margin-bottom: 12px;
  font-weight: 700;
}

.permission-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
  padding: 15px;
  background: #FFF5F7;
  border-radius: 8px;
  border: 1px solid #FFE4E1;
}

.permission-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #333;
  cursor: pointer;
  padding: 4px;
}

.permission-item:hover {
  color: #FF1493;
}

.permission-item input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
  accent-color: #FF69B4;
  flex-shrink: 0;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 2px solid #FFE4E1;
}
</style>
